package no.rodland.acc.db;

import org.joda.time.DateTime;

import no.rodland.acc.model.Bank;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Aug 2, 2010 3:57:52 PM
 * @Author: fmr
 */
public class SqlGenerator {
    private static final int BUDGET_AFTER_BANK_DAYS = 30;
    private static final int BUDGET_BEFORE_BANK_DAYS = 30;
    private static final int BUDGET_AFTER_BANK_AMOUNT = 500;
    private static final int BUDGET_BEFORE_BANK_AMOUNT = 500;

    public static String getBudgetForBank(Bank bank) {
        if (bank == null || bank.getDate() == null) {
            return getEmptySet("budget");
        }
        DateTime date = bank.getDate();
        String before = DbUtil.getSqlDate(date.minusDays(BUDGET_BEFORE_BANK_DAYS));
        String after = DbUtil.getSqlDate(date.plusDays(BUDGET_AFTER_BANK_DAYS));
        return "select * from budget where date >= '" + before + "' and date <= '" + after + "' and is_matched != 'Y' order by date";
    }

    private static String getEmptySet(String tableName) {
        return "select * from " + tableName + " where 1 = 0";
    }

    public static String getNextBank() {
        return "select * from bank where is_budgeted != 'Y' order by use_date asc limit 1";
    }

    public static String getById(int id, String tableName) {
        return "select * from " + tableName + " where id = " + id;
    }

    public static String getLastInsertId() {
        return "select LAST_INSERT_ID()";
    }

    public static String getStar(String tableName) {
        return "select * from " + tableName;
    }

    public static String getBank(DateTime date) {
        String sql = getStar("bank");
        String where = "";
        if (date != null) {
            String dt = DbUtil.getSqlDate(date);
            where = " where use_date >= '" + dt + "'";
        }
        sql = sql + where;
        return sql;
    }
}
